<?php
/**
 * 需要登录才可访问的用户相关接口
 */

namespace App\Http\Controllers\Home\API;

use App\Http\Controllers\TokenController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Services\OSS;

class UserNeedTokenController extends TokenController
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 申请正式用户编辑认证资料
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function editUserAuthFile(Request $request)
    {
//        $userRole = $this->loginUserInfo->user_role;
//        if($userRole==1) echo json_encode(['code'=>-1006,'msg'=>'权限不足']);

        $wechat_id = $request->input('wechat_id');
        $mobile = $request->input('mobile');
        $auth_img = $request->input('auth_img');
        if(!\Helpers::isMobile($mobile) || empty($wechat_id)) return json_encode(['code'=>-1002,'msg'=>'参数不合法']);

        //多图上传,==修改，由前端传递图片地址
        if(!empty($auth_img)){
            $auth_img = json_decode($auth_img);
            $data['status'] = 1;
            $data['member_id'] = $this->loginUserInfo->id;
            foreach ($auth_img as $k => $v){
                unset($data['img']);
                unset($data['create_time']);
                $data['img'] = $v->auth_img;
                $data['create_time'] = time();
                //插入用户认证照片
                DB::table('member_auth_img')->insert($data);
            }
        }
        //多图上传,==修改，由前端传递图片地址
//        $imgType = ['image/jpeg','image/gif','image/png','image/jpg'];
//        if(!empty($_FILES['auth_img'])){
//
//            $data['status'] = 1;
//            $data['member_id'] = $this->loginUserInfo->id;
//            foreach ($_FILES['auth_img']['error'] as $k => $v)
//            {
//                if($v > 0)
//                {
//                    return json_encode(['code'=>-1008,'msg'=>'上传文件失败【第'.($k+1).'张】']);
//                }
////                else if(!in_array($_FILES['auth_img']['type'][$k],$imgType)){
////                    return json_encode(['code'=>-1009,'msg'=>'上传文件格式错误【第'.($k+1).'张】']);
////                }
//                else{
//                    $path = $_FILES['auth_img']['tmp_name'][$k];
//                    $content_type = $_FILES['auth_img']['type'][$k];
//                    $ex = explode('.',$_FILES['auth_img']['name'][$k]);
//                    $ex = !empty($ex[1]) ? $ex[1] : '';
//                    $file_name = $data['member_id'].'_'.date('Y-m-d-H-i-s',$data['create_time']).rand(0,10000).'.'.$ex;
//                    $content = file_get_contents($path);
//                    $bucket_name = config('oss.bucketName');
//                    $res = OSS::publicUploadContent($bucket_name, $file_name, $content, ['ContentType' => $content_type]);//设置HTTP头
//                    //获取公开文件URL
//                    $url = OSS::getPublicObjectURL($bucket_name, $file_name);
//                    $datas['img'][$k] = $url;
//                    unset($data['img']);
//                    unset($data['create_time']);
//                    $data['img'] = $url;
//                    $data['create_time'] = time();
//                    //插入用户认证照片
//                    DB::table('member_auth_img')->insert($data);
//                }
//            }
//        }

        //手机号不能重复！
        $findUser = DB::table('member')->where('mobile',$mobile)->where('status','!=',3)->where('id','!=',$this->loginUserInfo->id)->first();
        if(!empty($findUser)) return json_encode(['code'=>-1004,'msg'=>'手机号已存在']);

        $upArr['mobile'] = $mobile;
        $upArr['wechat_id'] = $wechat_id;
        $upArr['auth_status'] = 1;
        $upArr['user_role'] = 2;
        $upArr['auth_create_time'] = time();

        $res = DB::table('member')->where('id',$this->loginUserInfo->id)->update($upArr);
        if($res){
            echo json_encode(['code'=>1,'msg'=>'SUCCESS']);
        }else{
            echo json_encode(['code'=>-1001,'msg'=>'服务器异常']);
        }
    }

    /**
     * 获取用户认证审核结果
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function getUserAuthResult(Request $request)
    {
        $result = array(
            'auth_status' => $this->loginUserInfo->auth_status,
            'reject_reason' => $this->loginUserInfo->reject_reason,
        );
        echo json_encode(['code'=>1,'msg'=>'SUCCESS','data'=>$result]);
    }

    /**
     * 我的提现帐户
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function getUserWithdrawAccount(Request $request)
    {
        $findAccount = DB::table('member_withdraw_account')->select('mobile','alipay_account','alipay_username')->where('member_id',$this->loginUserInfo->id)->first();

        echo json_encode(['code'=>1,'msg'=>'SUCCESS','data'=>$findAccount]);
    }

    /**
     * 新增/修改我的提现帐户
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function editUserWithdrawAccount(Request $request)
    {
        $data['alipay_account'] = $request->input('alipay_account');
        $data['alipay_username'] = $request->input('alipay_username');
        $data['mobile'] = $this->loginUserInfo->mobile;
        $data['create_time'] = time();

        if(empty($data['alipay_account']) || empty($data['alipay_username'])) return json_encode(['code'=>-1002,'msg'=>'参数不合法']);

        $findAccount = DB::table('member_withdraw_account')->where('member_id',$this->loginUserInfo->id)->first();
        if(!empty($findAccount)){
            DB::table('member_withdraw_account')->where('id',$findAccount->id)->update($data);
        }else{
            $data['member_id'] = $this->loginUserInfo->id;
            DB::table('member_withdraw_account')->insert($data);
        }

        echo json_encode(['code'=>1,'msg'=>'SUCCESS']);
    }

    /**
     * 我的-主播
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function getAnchorInfo(Request $request)
    {
        //验证sign合法性
        $isValidSign = $this->checkSign();
        if(empty($isValidSign)) exit(json_encode(['code'=>-9005,'msg'=>'sign无效']));
        //验证sign合法性

        if($this->loginUserInfo->auth_status != 2){
            $user_role = 2;
        }else{
            $user_role = $this->loginUserInfo->user_role;
        }
        $result = array(
            'username' => empty($this->loginUserInfo->username) ? '未取名' : $this->loginUserInfo->username,
            'sign' => $this->loginUserInfo->sign,
            'level' => $this->getUserLevel($this->loginUserInfo->id),
            'price' => $this->loginUserInfo->price,
            'avatar' => empty($this->loginUserInfo->avatar) ? '' : $this->loginUserInfo->avatar,
            'user_role' => $user_role,
            'first_free' => $this->loginUserInfo->first_free,
            'weibo' => $this->loginUserInfo->weibo,
            'douyin' => $this->loginUserInfo->douyin
        );
        //粉丝数
        $result['fans'] =  \Helpers::getUserFans($this->loginUserInfo->id);
        //关注数
        $result['focus'] =  \Helpers::getUserFocus($this->loginUserInfo->id);
        //E币数
        $result['e_money'] = \Helpers::getUserLeftMoney($this->loginUserInfo->id);
        echo json_encode(['code'=>1,'msg'=>'SUCCESS','data'=>$result]);
    }

    /**
     * 我的粉丝
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function getAnchorFans(Request $request)
    {
        //粉丝
        $fans =  DB::table('member_fans')
            ->select('member.id as fans_id','member.user_role','member.avatar','member.mobile','member.username')
            ->leftJoin('member','member.id','=','member_fans.member_id_z')
            ->where('member_fans.member_id_b',$this->loginUserInfo->id)
            ->where('member.status',1)
            ->where('member_fans.type',1)
            ->orderBy('member_fans.create_time','desc')
            ->get();
        if(!empty($fans)){
            foreach ($fans as $k => $v){
                $fans[$k]->gj = 'yg';
                $fans[$k]->level = $this->getUserLevel($v->fans_id);
            }
        }
        echo json_encode(['code'=>1,'msg'=>'SUCCESS','data'=>$fans]);
    }

    /**
     * 粉丝移入黑名单
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function delAnchorFans(Request $request)
    {
        $fans_id = $request->input('fans_id');
        if(empty($fans_id)) return json_encode(['code'=>-1002,'msg'=>'参数不合法']);
        $findFans = DB::table('member_fans')->where('member_id_b',$this->loginUserInfo->id)->where('member_id_z',$fans_id)->where('type',1)->first();
        if(empty($findFans)) return json_encode(['code'=>-1007,'msg'=>'粉丝不存在']);

        $upArr = array('type'=>3);
        DB::table('member_fans')->where('id',$findFans->id)->update($upArr);

        echo json_encode(['code'=>1,'msg'=>'SUCCESS']);
    }

    /**
     * 我的E币
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function getMyEmoney(Request $request)
    {
        $e_money =  DB::table('member_recharge')->select('create_time','e_money','type','pay_type')->where('member_id',$this->loginUserInfo->id)->where('operate_status',1)->orderBy('id','desc')->get();
        echo json_encode(['code'=>1,'msg'=>'SUCCESS','data'=>$e_money]);
    }

    /**
     * 我的-收入明细
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function getMyIncome(Request $request)
    {
        $page = $request->input('page');
        if(empty($page)) $page = 1;
        $start = ($page - 1) * 10;

        $e_money =  DB::table('member_recharge')->select('create_time','e_money','type','chat_time','pay_type')->where('member_id',$this->loginUserInfo->id)->where('operate_status',1)->where('e_money','>',0)->orderBy('id','desc')->skip($start)->take(10)->get();
        echo json_encode(['code'=>1,'msg'=>'SUCCESS','data'=>$e_money]);
    }

    /**
     * 我的-支出明细
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function getMyExpend(Request $request)
    {
        $page = $request->input('page');
        if(empty($page)) $page = 1;
        $start = ($page - 1) * 10;

        $e_money =  DB::table('member_consume')->select('create_time','e_money','type','chat_time')->where('member_id',$this->loginUserInfo->id)->orderBy('id','desc')->skip($start)->take(10)->get();
        echo json_encode(['code'=>1,'msg'=>'SUCCESS','data'=>$e_money]);
    }

    /**
     * 我的-提现明细
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function getMyWithdraw(Request $request)
    {
        $page = $request->input('page');
        if(empty($page)) $page = 1;
        $start = ($page - 1) * 10;

        $e_money =  DB::table('member_recharge')->select('create_time','e_money')->where('member_id',$this->loginUserInfo->id)->where('operate_status',1)->where('type',5)->orderBy('id','desc')->skip($start)->take(10)->get();
        echo json_encode(['code'=>1,'msg'=>'SUCCESS','data'=>$e_money]);
    }

    /**
     * 上传小视频
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function addVideoFile(Request $request)
    {
        $data['type'] = $request->input('type');

        if(empty($data['type']) || empty($_FILES['video'])) return json_encode(['code'=>-1002,'msg'=>'参数不合法']);

        //多视频上传
        $data['status'] = 1;
        $data['member_id'] = $this->loginUserInfo->id;
        $data['create_time'] = time();
        foreach ($_FILES['video']['error'] as $k => $v)
        {
            if($v > 0)
            {
                return json_encode(['code'=>-1008,'msg'=>'上传文件失败【第'.($k+1).'张】']);
            }else{
                $path = $_FILES['video']['tmp_name'][$k];
                $content_type = $_FILES['video']['type'][$k];
                $ex = explode('.',$_FILES['video']['name'][$k]);
                $ex = !empty($ex[1]) ? $ex[1] : '';
                $file_name = $data['member_id'].'_'.date('Y-m-d-H-i-s',$data['create_time']).rand(0,10000).'.'.$ex;
                $content = file_get_contents($path);
                $bucket_name = config('oss.bucketName');
                $res = OSS::publicUploadContent($bucket_name, $file_name, $content, ['ContentType' => $content_type]);//设置HTTP头
                //获取公开文件URL
                $url = OSS::getPublicObjectURL($bucket_name, $file_name);
                $datas['video'][$k] = $url;
                unset($data['video']);
                unset($data['create_time']);
                $data['video'] = $url;
                $data['create_time'] = time();

                $path_img = $_FILES['img']['tmp_name'][$k];
                $content_type_img = $_FILES['img']['type'][$k];
                $ex_img = explode('.',$_FILES['img']['name'][$k]);
                $ex_img = !empty($ex_img[1]) ? $ex_img[1] : '';
                $file_name_img = $data['member_id'].'_'.date('Y-m-d-H-i-s',$data['create_time']).rand(0,10000).'.'.$ex_img;
                $content_img = file_get_contents($path_img);
                $res_img = OSS::publicUploadContent($bucket_name, $file_name_img, $content_img, ['ContentType' => $content_type_img]);//设置HTTP头
                //获取公开文件URL
                $url_img = OSS::getPublicObjectURL($bucket_name, $file_name_img);
                unset($data['img']);
                $data['img'] = $url_img;

                //插入用户认证照片
                DB::table('member_video')->insert($data);
            }
        }
        echo json_encode(['code'=>1,'msg'=>'SUCCESS']);
    }



    /**
     * 上传艺术照
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function addImgFile(Request $request)
    {
        if(empty($_FILES['img'])) return json_encode(['code'=>-1002,'msg'=>'参数不合法']);

        //多视频上传
        $data['status'] = 1;
        $data['member_id'] = $this->loginUserInfo->id;
        $data['create_time'] = time();

        //多图上传
        $imgType = ['image/jpeg','image/gif','image/png','image/jpg'];
        foreach ($_FILES['img']['error'] as $k => $v)
        {
            if($v > 0)
            {
                return json_encode(['code'=>-1008,'msg'=>'上传文件失败【第'.($k+1).'张】']);
            }else{
                $path = $_FILES['img']['tmp_name'][$k];
                $content_type = $_FILES['img']['type'][$k];
                $ex = explode('.',$_FILES['img']['name'][$k]);
                $ex = !empty($ex[1]) ? $ex[1] : '';
                $file_name = $data['member_id'].'_'.date('Y-m-d-H-i-s',$data['create_time']).rand(0,10000).'.'.$ex;
                $content = file_get_contents($path);
                $bucket_name = config('oss.bucketName');
                $res = OSS::publicUploadContent($bucket_name, $file_name, $content, ['ContentType' => $content_type]);//设置HTTP头
                //获取公开文件URL
                $url = OSS::getPublicObjectURL($bucket_name, $file_name);
                $datas['img'][$k] = $url;
                unset($data['img']);
                unset($data['create_time']);
                $data['img'] = $url;
                $data['create_time'] = time();
                //插入用户认证照片
                DB::table('member_img')->insert($data);
            }
        }

        echo json_encode(['code'=>1,'msg'=>'SUCCESS']);
    }

    /**
     * 获取我的艺术照
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function getUserImg(Request $request)
    {
        $img = DB::table('member_img')->select('id','img','create_time')->where('member_id',$this->loginUserInfo->id)->where('status',1)->orderBy('create_time','desc')->get();

        echo json_encode(['code'=>1,'msg'=>'SUCCESS','data'=>$img]);
    }

    /**
     * 删除艺术照
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function delUserImg(Request $request)
    {
        $id = $request->input('id');

        if(empty($id)) return json_encode(['code'=>-1002,'msg'=>'参数不合法']);

        $findData = DB::table('member_img')->where('member_id',$this->loginUserInfo->id)->where('id',$id)->where('status',1)->first();
        if(empty($findData)) return json_encode(['code'=>-1009,'msg'=>'数据不存在']);

        DB::table('member_img')->where('id',$findData->id)->update(array('status'=>3));
        echo json_encode(['code'=>1,'msg'=>'SUCCESS']);
    }

    /**
     * 删除小视频
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function delUserVideo(Request $request)
    {
        $id = $request->input('id');

        if(empty($id)) return json_encode(['code'=>-1002,'msg'=>'参数不合法']);

        $findData = DB::table('member_video')->where('member_id',$this->loginUserInfo->id)->where('id',$id)->where('status',1)->first();
        if(empty($findData)) return json_encode(['code'=>-1009,'msg'=>'数据不存在']);

        DB::table('member_video')->where('id',$findData->id)->update(array('status'=>3));
        echo json_encode(['code'=>1,'msg'=>'SUCCESS']);
    }

    /**
     * 申请正式用户编辑认证资料
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function editAnchorAuthFile(Request $request)
    {
//        $userRole = $this->loginUserInfo->user_role;
//        if($userRole==1) echo json_encode(['code'=>-1006,'msg'=>'权限不足']);

        $username = $request->input('username');
        $mobile = $request->input('mobile');
        $height = $request->input('height');
        $weight = $request->input('weight');
        $birth = $request->input('birth');
        $city = $request->input('city');
        $job = $request->input('job');
        $apperance = $request->input('apperance');
        $sign = $request->input('sign');
        $gender = $request->input('gender');
        $auth_img = $request->input('auth_img');

        if(!\Helpers::isMobile($mobile) || empty($username) || empty($height) || empty($weight) || empty($birth) || empty($city) || empty($job) || empty($apperance) || empty($sign)) return json_encode(['code'=>-1002,'msg'=>'参数不合法']);

        //多图上传,==修改，由前端传递图片地址
        if(!empty($auth_img)){
            $auth_img = json_decode($auth_img);
            $data['status'] = 1;
            $data['member_id'] = $this->loginUserInfo->id;
            foreach ($auth_img as $k => $v){
                unset($data['img']);
                unset($data['create_time']);
                $data['img'] = $v->auth_img;
                $data['create_time'] = time();
                //插入用户认证照片
                DB::table('member_auth_img')->insert($data);
            }
        }
//        //多图上传
//        if(!empty($_FILES['auth_img'])){
//
//            $data['status'] = 1;
//            $data['member_id'] = $this->loginUserInfo->id;
//            foreach ($_FILES['auth_img']['error'] as $k => $v)
//            {
//                if($v > 0)
//                {
//                    return json_encode(['code'=>-1008,'msg'=>'上传文件失败【第'.($k+1).'张】']);
//                }else{
//                    $path = $_FILES['auth_img']['tmp_name'][$k];
//                    $content_type = $_FILES['auth_img']['type'][$k];
//                    $ex = explode('.',$_FILES['auth_img']['name'][$k]);
//                    $ex = !empty($ex[1]) ? $ex[1] : '';
//                    $file_name = $data['member_id'].'_'.date('Y-m-d-H-i-s',$data['create_time']).rand(0,10000).'.'.$ex;
//                    $content = file_get_contents($path);
//                    $bucket_name = config('oss.bucketName');
//                    $res = OSS::publicUploadContent($bucket_name, $file_name, $content, ['ContentType' => $content_type]);//设置HTTP头
//                    //获取公开文件URL
//                    $url = OSS::getPublicObjectURL($bucket_name, $file_name);
//                    $datas['img'][$k] = $url;
//                    unset($data['img']);
//                    unset($data['create_time']);
//                    $data['img'] = $url;
//                    $data['create_time'] = time();
//                    //插入用户认证照片
//                    DB::table('member_auth_img')->insert($data);
//                }
//            }
//        }

        //手机号不能重复！
        $findUser = DB::table('member')->where('mobile',$mobile)->where('status','!=',3)->where('id','!=',$this->loginUserInfo->id)->first();
        if(!empty($findUser)) return json_encode(['code'=>-1004,'msg'=>'手机号已存在']);

        $upArr['mobile'] = $mobile;
        $upArr['username'] = $username;
        $upArr['height'] = $height;
        $upArr['weight'] = $weight;
        $upArr['birth'] = $birth;
        $upArr['city'] = $city;
        $upArr['job'] = $job;
        $upArr['apperance'] = $apperance;
        $upArr['sign'] = $sign;
        $upArr['auth_status'] = 1;
        $upArr['user_role'] = 3;
        $upArr['auth_create_time'] = time();
        $upArr['gender'] = $gender;

        $res = DB::table('member')->where('id',$this->loginUserInfo->id)->update($upArr);
        if($res){
            echo json_encode(['code'=>1,'msg'=>'SUCCESS']);
        }else{
            echo json_encode(['code'=>-1001,'msg'=>'服务器异常']);
        }
    }

    /**
     * 获取礼物列表
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function getPresent(Request $request)
    {
        $list['present'] = DB::table('present')->select('id','name',DB::raw('concat("'.$this->baseUrl.'",img) as present_img'),'e_money')->where('status',1)->orderBy('order','asc')->get();
        //获取当前时间的周星礼物
        $time = time();
        $list['week'] = DB::table('active')
                    ->select('id as week_id','gift_name as week_name',DB::raw('concat("'.$this->baseUrl.'",shop_img) as week_img'),'gift_price as week_price','id')
                    ->where('start_time','<',$time)
                    ->where('end_time','>',$time)
                    ->orderBy('sort','asc')
                    ->get();
        if(!empty($list['week'])){
            foreach ($list['week'] as $k => $v){
                $list['week'][$k]->id = $v->id + 1000;
                $list['week'][$k]->week_id = $v->week_id + 1000;
            }
        }
        echo json_encode(['code'=>1,'msg'=>'SUCCESS','data'=>$list]);
    }



    /**
     * 绑定手机
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function bindMobile(Request $request)
    {
        $mobile = $request->input('mobile');
        $code = $request->input('code');  //验证码
        $password = $request->input('password');
        $auth_type = $request->input('auth_type'); //第三方登录类型，1：微信，2：QQ
        $openid = $request->input('openid');

        if(strlen($password) != 32 || !\Helpers::isMobile($mobile) || empty($code) || !in_array($auth_type,[1,2]) || empty($openid)) return json_encode(['code'=>-1002,'msg'=>'参数不合法']);
//        if($code != '1234') return json_encode(['code'=>-1003,'msg'=>'验证码有误']);

        //验证短信验证码
        $checkCode = $this->checkSms($mobile,$code);
        if($checkCode == 0) return json_encode(['code'=>-1003,'msg'=>'验证码有误']);

        //传过来的加密密码再md5加密一次
        $password = md5($password);

        if($mobile == $this->loginUserInfo->mobile) return json_encode(['code'=>-1010,'msg'=>'已绑定当前手机号']);

        $findUser = DB::table('member')->where('mobile',$mobile)->where('status',1)->first();

        \Cache::forget('sms_'.$mobile);  //让验证码失效

        //先查找手机号存在否，若存在，判断是否是当前用户。如果不是，判断绑定。如果是，做check
        if(!empty($findUser)){
            if($findUser->id == $this->loginUserInfo->id){
                //同一个用户，更新openid和password
                if($auth_type==1){
                    $upArr['openid'] = $openid;
                }else{
                    $upArr['qqid'] = $openid;
                }
                $upArr['auth_type'] = $auth_type;
                $upArr['password'] = $password;
                $updateOpe = DB::table('member')->where('id',$this->loginUserInfo->id)->update($upArr);
                if($updateOpe){
                    echo json_encode(['code'=>1,'msg'=>'SUCCESS']);
                }else{
                    echo json_encode(['code'=>-1001,'msg'=>'服务器异常']);
                }
            }else{
                //不是同一个用户
                if($auth_type==1){
                    if($findUser->openid != $openid){
                        return json_encode(['code'=>-1011,'msg'=>'当前手机已被其他帐号绑定']);
                    }
                }else{
                    if($findUser->qqid != $openid){
                        return json_encode(['code'=>-1011,'msg'=>'当前手机已被其他帐号绑定']);
                    }
                }
                return json_encode(['code'=>-1010,'msg'=>'已绑定当前手机号']);
            }
        }else{
            //绑定手机
            $upArr['mobile'] = $mobile;
            $upArr['password'] = $password;
            $updateOpe = DB::table('member')->where('id',$this->loginUserInfo->id)->update($upArr);
            if($updateOpe){
                echo json_encode(['code'=>1,'msg'=>'SUCCESS']);
            }else{
                echo json_encode(['code'=>-1001,'msg'=>'服务器异常']);
            }
        }
    }

    /**
     * 编辑个人资料
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function editUserFile(Request $request)
    {
        $username = $request->input('username');
        $height = $request->input('height');
        $weight = $request->input('weight');
        $city = $request->input('city');
        $apperance = $request->input('apperance');
        $sign = $request->input('sign');

        if(!empty($_FILES['avatar'])){
            if($_FILES['avatar']['error'] > 0)
            {
                return json_encode(['code'=>-1008,'msg'=>'上传文件失败']);
            }else{
                $path = $_FILES['avatar']['tmp_name'];
                $content_type = $_FILES['avatar']['type'];
                $ex = explode('.',$_FILES['avatar']['name']);
                $ex = !empty($ex[1]) ? $ex[1] : '';
                $file_name = $this->loginUserInfo->id.'_'.date('Y-m-d H:i:s',time()).rand(0,10000).'.'.$ex;
                $content = file_get_contents($path);
                $bucket_name = config('oss.bucketName');
                $res = OSS::publicUploadContent($bucket_name, $file_name, $content, ['ContentType' => $content_type]);//设置HTTP头
                //获取公开文件URL
                $url = OSS::getPublicObjectURL($bucket_name, $file_name);
                $upArr['avatar'] = $url;
            }
        }
        if(!empty($username)){
            $upArr['username'] = $username;
        }
        if(!empty($sign)){
            $upArr['sign'] = $sign;
        }
        if(!empty($height)){
            $upArr['height'] = $height;
        }
        if(!empty($weight)){
            $upArr['weight'] = $weight;
        }
        if(!empty($city)){
            $upArr['city'] = $city;
        }
        if(!empty($apperance)){
            $upArr['apperance'] = $apperance;
        }

        if(!empty($upArr)){
            $res = DB::table('member')->where('id',$this->loginUserInfo->id)->update($upArr);
            if($res){
                echo json_encode(['code'=>1,'msg'=>'SUCCESS']);
            }else{
                echo json_encode(['code'=>-1001,'msg'=>'服务器异常']);
            }
        }else{
            echo json_encode(['code'=>-1002,'msg'=>'参数不合法']);
        }
    }

    /**
     * 删除我的提现帐户
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function delUserWithdrawAccount(Request $request)
    {
        $findAccount = DB::table('member_withdraw_account')->where('member_id',$this->loginUserInfo->id)->first();
        if(!empty($findAccount)){
            DB::table('member_withdraw_account')->where('id',$findAccount->id)->delete();
            echo json_encode(['code'=>1,'msg'=>'SUCCESS']);
        }else{
            echo json_encode(['code'=>-1009,'msg'=>'数据不存在']);
        }
    }

    /**
     * 价值申请 - 申请主播单价
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function userPriceApply(Request $request)
    {
        $data['price_apply'] = $request->input('price_apply');
        $data['price_status'] = 1;
        $data['price_apply_time'] = time();

        if(empty($data['price_apply'])) return json_encode(['code'=>-1002,'msg'=>'参数不合法']);

        $findAccount = DB::table('member')->where('id',$this->loginUserInfo->id)->first();
        if(!empty($findAccount)){
            DB::table('member')->where('id',$findAccount->id)->update($data);
            echo json_encode(['code'=>1,'msg'=>'SUCCESS']);
        }else{
            echo json_encode(['code'=>-1009,'msg'=>'数据不存在']);
        }
    }

    /**
     * 打赏用户
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function rewardUser(Request $request)
    {
        $present_id = $request->input('present_id');
        $anchor_id = $request->input('anchor_id');
        if(empty($present_id) || empty($anchor_id)) return json_encode(['code'=>-1002,'msg'=>'参数不合法']);

        //验证sign合法性
        $isValidSign = $this->checkSign($present_id);
        if(empty($isValidSign)) exit(json_encode(['code'=>-9005,'msg'=>'sign无效']));
        //验证sign合法性

        //不能给自己打赏
        if($anchor_id == $this->loginUserInfo->id) return json_encode(['code'=>-1002,'msg'=>'参数不合法']);

        //被打赏的用户必须是合法用户
        $findAnchor = DB::table('member')->where('id',$anchor_id)->where('status',1)->first();
        if(empty($findAnchor) ) return json_encode(['code'=>-1002,'msg'=>'参数不合法']);

        $left_money = \Helpers::getUserLeftMoney($this->loginUserInfo->id);
        if($left_money <= 0) return json_encode(['code'=>-1012,'msg'=>'E币不足']);

        if($present_id<1000){
            $findPresent = DB::table('present')->where('id',$present_id)->where('status',1)->first();
            if(empty($findPresent)) return json_encode(['code'=>-1009,'msg'=>'数据不存在']);
            $e_money = $findPresent->e_money;
            $insertArr['reward_type'] = 0;
        }else{
            $present_idb = $present_id-1000;
            $findPresent = DB::table('active')->where('id',$present_idb)->where('status',2)->first();
            if(empty($findPresent)) return json_encode(['code'=>-1009,'msg'=>'数据不存在']);
            $e_money = $findPresent->gift_price;
            $insertArr['reward_type'] = 1;
        }

        if($e_money > $left_money) return json_encode(['code'=>-1012,'msg'=>'E币不足']);

        $insertArr['member_id'] = $this->loginUserInfo->id;
        $insertArr['member_id_b'] = $anchor_id;
        $insertArr['present_id'] = $present_id;
        $insertArr['type'] = 2;
        $insertArr['e_money'] = $e_money;
        $insertArr['create_time'] = time();

        //打赏，时间限制：同一个用户3秒内只能送礼一次
        $timeDiff = $insertArr['create_time']-3;
        $findLatestConsume = DB::table('member_consume')->where('member_id',$insertArr['member_id'])->where('create_time','>',$timeDiff)->where('type',2)->orderBy('id','desc')->first();
        if(!empty($findLatestConsume)){
            return json_encode(['code'=>-1017,'msg'=>'操作过于频繁']);
        }

        $insertDb = DB::table('member_consume')->insertGetId($insertArr);
        if(!empty($insertDb)){
            //往e币表加数据
            $insertR['member_id'] = $this->loginUserInfo->id;
            $insertR['create_time'] = time();
            $insertR['e_money'] = '-'.$e_money;
            $insertR['operate_status'] = 1;
            $insertR['type'] = 4;
            $insertR['consume_id'] = $insertDb;

            $insertReDb = DB::table('member_recharge')->insertGetId($insertR);

            //主播增加E币
            $insertRA['member_id'] = $anchor_id;
            $insertRA['create_time'] = time();
            $insertRA['e_money'] = $e_money;
            $insertRA['operate_status'] = 1;
            $insertRA['type'] = 4;
            $insertRA['consume_id'] = $insertDb;
            DB::table('member_recharge')->insertGetId($insertRA);

            //给上级E币增加分成
            $this->pidShared($this->loginUserInfo->id,$e_money);
            //推送信息
            //获取用户信息
            $userInfo = DB::table('member')->where('id',$this->loginUserInfo->id)->select('avatar','username')->first();
            //获取主播信息
            $anchorInfo = DB::table('member')->where('id',$anchor_id)->select('avatar','username')->first();
            $sendInfo['type'] = 3;
            $sendInfo['avatar'] = !empty($userInfo->avatar) ? $userInfo->avatar : '';
            $sendInfo['username'] = !empty($userInfo->username) ? $userInfo->username : '';
            $sendInfo['anchorname'] = !empty($anchorInfo->username) ? $anchorInfo->username : '';
            $sendInfo['giftimage'] = $present_id<1000 ? __BASE__.$findPresent->img : __BASE__.$findPresent->shop_img;
            $sendInfo['money'] = '';
            $help = new \Helpers();
            $help->sendJpush(json_encode($sendInfo));
            echo json_encode(['code'=>1,'msg'=>'SUCCESS']);
        }else{
            echo json_encode(['code'=>-1001,'msg'=>'服务器异常']);
        }
    }

    /**
     * 用户提现
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function userWithdraw(Request $request)
    {
        $e_money = $request->input('e_money');
        if(empty($e_money) || $e_money<=0) return json_encode(['code'=>-1002,'msg'=>'参数不合法']);

        $left_money = \Helpers::getUserLeftMoney($this->loginUserInfo->id);
        if($left_money <= 0) return json_encode(['code'=>-1012,'msg'=>'E币不足']);

        if($e_money>$left_money) return json_encode(['code'=>-1012,'msg'=>'E币不足']);

        $findWithdrawAccount = DB::table('member_withdraw_account')->where('member_id',$this->loginUserInfo->id)->first();
        if(empty($findWithdrawAccount)) return json_encode(['code'=>-1013,'msg'=>'提现帐户不存在']);

        $insertArr['member_id'] = $this->loginUserInfo->id;
        $insertArr['mobile'] = $findWithdrawAccount->mobile;
        $insertArr['e_money'] = $e_money;
        $insertArr['alipay_account'] = $findWithdrawAccount->alipay_account;
        $insertArr['alipay_username'] = $findWithdrawAccount->alipay_username;
        $insertArr['status'] = 0;
        $insertArr['apply_time'] = time();

        $insertDb = DB::table('member_withdraw')->insertGetId($insertArr);
        if(!empty($insertDb)){
            //往e币表加数据
            $insertR['member_id'] = $this->loginUserInfo->id;
            $insertR['create_time'] = time();
            $insertR['e_money'] = '-'.$e_money;
            $insertR['operate_status'] = 0;
            $insertR['type'] = 5;
            $insertR['withdraw_id'] = $insertDb;

            $insertReDb = DB::table('member_recharge')->insertGetId($insertR);
            echo json_encode(['code'=>1,'msg'=>'SUCCESS']);
        }else{
            echo json_encode(['code'=>-1001,'msg'=>'服务器异常']);
        }
    }

    /**
     * 设置主播限免
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function setAnchorFree(Request $request)
    {
        $free = $request->input('is_free');
        if(!isset($free)) return json_encode(['code'=>-1002,'msg'=>'参数不合法']);
        $member =  DB::table('member')->where('id',$this->loginUserInfo->id)->where('status',1)->first();
        if(empty($member)) return json_encode(['code'=>-1009,'msg'=>'数据不存在']);

        $leftMoney = \Helpers::getUserLeftMoney($this->loginUserInfo->id);
//        if($leftMoney<100) return json_encode(['code'=>-1014,'msg'=>'余额不足100E币']);

        $upArr = array(
            'first_free' => $free,
            'free_time' => time()
        );
        $res = DB::table('member')->where('id',$this->loginUserInfo->id)->update($upArr);
        if($res){
            echo json_encode(['code'=>1,'msg'=>'SUCCESS']);
        }else{
            echo json_encode(['code'=>-1001,'msg'=>'服务器异常']);
        }

    }


    /**
     * 关注/不喜欢/取消关注主播
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function addAnchorFans(Request $request)
    {
        $member_id = $request->input('member_id');
        $type = $request->input('type');  //1喜欢，2不喜欢，3取消关注
        if(empty($member_id) || empty($type) || !in_array($type,[1,2,3])) return json_encode(['code'=>-1002,'msg'=>'参数不合法']);

        $findMember = DB::table('member')->where('id',$member_id)->where('status',1)->first();
        if(empty($findMember)) return json_encode(['code'=>-1009,'msg'=>'数据不存在']);

        $findFans = DB::table('member_fans')->where('member_id_b',$member_id)->where('member_id_z',$this->loginUserInfo->id)->first();
        if(empty($findFans)){
            //喜欢or不喜欢
            $insertArr = array(
                'member_id_z' => $this->loginUserInfo->id,
                'member_id_b' => $member_id,
                'create_time' => time(),
                'type' => $type
            );
            DB::table('member_fans')->insert($insertArr);
        }else{
            //已经有记录了，直接更新
            if($type==3){
                //取消关注就直接删除记录
                DB::table('member_fans')->where('id',$findFans->id)->delete();
            }else{
                $upArr = array(
                    'type' => $type,
                    'create_time' => time()
                );
                DB::table('member_fans')->where('id',$findFans->id)->update($upArr);
            }
        }
        echo json_encode(['code'=>1,'msg'=>'SUCCESS']);
    }

    /**
     * 收藏视频
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function addVideoColletion(Request $request)
    {
        $video_id = $request->input('video_id');
        $type = $request->input('type');  //1收藏，2取消收藏

        if(empty($video_id) || empty($type) || !in_array($type,[1,2])) return json_encode(['code'=>-1002,'msg'=>'参数不合法']);

        $findOne = DB::table('member_video')->where('id',$video_id)->first();
        if(empty($findOne)) return json_encode(['code'=>-1009,'msg'=>'数据不存在']);

        $findColletion = DB::table('member_video_colletion')->where('member_id',$this->loginUserInfo->id)->where('video_id',$video_id)->first();
        if($type==1){
            if(empty($findFans)){
                //喜欢or不喜欢
                $insertArr = array(
                    'member_id' => $this->loginUserInfo->id,
                    'video_id' => $video_id,
                    'create_time' => time(),
                );
                DB::table('member_video_colletion')->insert($insertArr);
                return json_encode(['code'=>1,'msg'=>'SUCCESS']);
            }else{
                //已经收藏过了
                return json_encode(['code'=>-1015,'msg'=>'已进行过此操作']);
            }
        }else{
            if(!empty($findColletion)){
                //取消收藏就直接删除记录
                DB::table('member_video_colletion')->where('id',$findColletion->id)->delete();
                return json_encode(['code'=>1,'msg'=>'SUCCESS']);
            }else{
                //数据不存在
                return json_encode(['code'=>-1009,'msg'=>'数据不存在']);
            }
        }
    }

    /**
     * 获取用户资产
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function getUserAssets(Request $request)
    {
        //钱包 wallet
        $rechargeMoney = \Helpers::getUserLeftMoney($this->loginUserInfo->id);
        //获取用户充值的钱
        $inMoney = \Helpers::getUserRechargeMoney($this->loginUserInfo->id);
        //主播
        if($this->loginUserInfo->user_role==3){
            $res['wallet'] = $rechargeMoney; //钱包
            $res['canWithdraw'] = $rechargeMoney-$inMoney;  //可提现
            $res['totalAssets'] = $rechargeMoney;  //资产总额
        }else{
            $res['wallet'] = $rechargeMoney;
            $res['canWithdraw'] = $rechargeMoney-$inMoney;
            $res['totalAssets'] = $rechargeMoney;
        }
        echo json_encode(['code'=>1,'msg'=>'SUCCESS','data'=>$res]);
    }

    /**
     * 我的通话
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function getUserOneByOneVideo(Request $request)
    {
        $page = $request->input('page');
        if(empty($page)) $page = 1;
        $start = ($page - 1) * 10;
        if($this->loginUserInfo->user_role == 3)
        {
            //获取1小时内注册用户
            $findStar = DB::table('admini_systeminfo')->select('cg','jg','yg')->first();
            $yg = $findStar->yg;
            $jg = $findStar->jg;
            $cg = $findStar->cg;
            $res = DB::table('member_consume')->select('e_money','chat_time','member_id_b as anchor_id','create_time','member_id','call_id')->where('member_id_b',$this->loginUserInfo->id)->where('type',1)->orderBy('id','desc')->skip($start)->take(10)->get();
            if(!empty($res)){
                foreach ($res as $k => $v){
                    $m[$k] = DB::table('member')->select('username','avatar','mobile')->where('id',$v->member_id)->first();
                    $res[$k]->username = $m[$k]->username;
                    $res[$k]->avatar = $m[$k]->avatar;
                    $res[$k]->level = $this->getUserLevel($v->member_id);
                    $res[$k]->mobile = $m[$k]->mobile;
                    $likeNum = DB::table('replay')
                        ->select(DB::raw('count(*) as like_num'))
                        ->where('feel',1)
                        ->where('anchor_id',$v->member_id)
                        ->first();
                    if($likeNum->like_num>=$yg && $likeNum->like_num<$jg){
                        $res[$k]->gj = 'yg';
                    }else if($likeNum->like_num>=$jg && $likeNum->like_num<$cg){
                        $res[$k]->gj = 'jg';
                    }else{
                        $res[$k]->gj = 'cg';
                    }
                }
            }
        }else{
            $res = DB::table('member_consume')->select('e_money','chat_time','member_id_b as anchor_id','create_time','call_id')->where('member_id',$this->loginUserInfo->id)->where('type',1)->orderBy('id','desc')->skip($start)->take(10)->get();
            if(!empty($res)){
                foreach ($res as $k => $v){
                    $m[$k] = DB::table('member')->select('username','avatar','mobile')->where('id',$v->anchor_id)->first();
                    $res[$k]->username = $m[$k]->username;
                    $res[$k]->avatar = $m[$k]->avatar;
                    $res[$k]->level = $this->getUserLevel($v->anchor_id);
                    $res[$k]->mobile = $m[$k]->mobile;
                }
            }
        }


        echo json_encode(['code'=>1,'msg'=>'SUCCESS','data'=>$res]);
    }

    public function getUserOneByOneVideoFail(Request $request)
    {
        $post = $request->all();
        if(empty($post['member_id'])) return json_encode(['code'=>-1,'msg'=>'缺少参数member_id有误']);
        if(empty($post['member_id_b'])) return json_encode(['code'=>-1,'msg'=>'缺少参数member_id_b有误']);
        if(empty($post['call_id'])) return json_encode(['code'=>-1,'msg'=>'缺少参数call_id有误']);
        $insert['member_id'] = intval($post['member_id']);
        $insert['member_id_b'] = intval($post['member_id_b']);
        $insert['call_id'] = intval($post['call_id']);
        $insert['create_time'] = time();
        $insert['type'] = 1;
        $insert['chat_time'] = 0;
        $res = DB::table('member_consume')->insertGetId($insert);
        if($res)
        {
            echo json_encode(['code'=>1,'msg'=>'成功']);
        }else{
            echo json_encode(['code'=>-1,'msg'=>'失败']);
        }
    }

    /**
     * 获取用户黑名单列表
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function getUserBlacks(Request $request)
    {
        $page = $request->input('page');
        if(empty($page)) $page = 1;
        $start = ($page - 1) * 10;

        $list =  DB::table('member_fans')
            ->select('member.id as black_id','member.user_role','member.avatar','member.username')
            ->leftJoin('member','member.id','=','member_fans.member_id_z')
            ->where('member_fans.member_id_b',$this->loginUserInfo->id)
            ->where('member.status',1)
            ->where('member_fans.type',3)
            ->orderBy('member_fans.create_time','desc')
            ->skip($start)->take(10)
            ->get();
        if(!empty($list)){
            foreach ($list as $k => $v){
                $list[$k]->gj = 'yg';
                $list[$k]->level = $this->getUserLevel($v->black_id);
            }
        }
        echo json_encode(['code'=>1,'msg'=>'SUCCESS','data'=>$list]);
    }

    /**
     * 粉丝移出黑名单
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function moveBlack(Request $request)
    {
        $fans_id = $request->input('black_id');
        if(empty($fans_id)) return json_encode(['code'=>-1002,'msg'=>'参数不合法']);

        $findFans = DB::table('member_fans')->where('member_id_b',$this->loginUserInfo->id)->where('member_id_z',$fans_id)->where('type',3)->first();
        if(empty($findFans)) return json_encode(['code'=>-1009,'msg'=>'数据不存在']);

        DB::table('member_fans')->where('id',$findFans->id)->delete();

        echo json_encode(['code'=>1,'msg'=>'SUCCESS']);
    }

    /**
     * 分成计划
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function planList(Request $request)
    {
        $page = $request->input('page');
        if(empty($page)) $page = 1;
        $start = ($page - 1) * 10;

        $plan_rate = DB::table('admini_systeminfo')
            ->select('anchor_proportions','plan_proportions')
            ->first();
        //我的推荐主播
        $data['list_anchor'] = DB::table('member')->select('id','username','avatar','user_role','create_time')->where('status',1)->where('pid',$this->loginUserInfo->id)->where('user_role',3)->where('auth_status',2)->skip($start)->take(10)->get();

        //我的推荐用户
        $data['list_user'] = DB::table('member')->select('id','username','avatar','user_role','create_time')->where('status',1)->where('pid',$this->loginUserInfo->id)->where('user_role','!=',3)->skip($start)->take(10)->get();

        $data['contribution_total'] = intval(\Helpers::getUserRechargeContribution($this->loginUserInfo->id)*$plan_rate->plan_proportions/100);
        $data['contribution_left'] = intval(\Helpers::getUserContribution($this->loginUserInfo->id)*$plan_rate->plan_proportions/100);
        $data['list_anchor_num'] = DB::table('member')->select('id','username','avatar','user_role','create_time')->where('status',1)->where('pid',$this->loginUserInfo->id)->where('user_role',3)->where('auth_status',2)->count();
        $data['list_user_num'] = DB::table('member')->select('id','username','avatar','user_role','create_time')->where('status',1)->where('pid',$this->loginUserInfo->id)->where('user_role','!=',3)->count();

        //累计贡献值
        if(!empty($data['list_anchor'])){
            foreach ($data['list_anchor'] as $k => $v){
                $data['list_anchor'][$k]->con_num = \Helpers::getUserContribution($v->id);
                $data['list_anchor'][$k]->level = $this->getUserLevel($v->id);
            }
        }
        if(!empty($data['list_user'])){
            foreach ($data['list_user'] as $k => $v){
                $data['list_user'][$k]->con_num = \Helpers::getUserContribution($v->id);
                $data['list_user'][$k]->level = $this->getUserLevel($v->id);
            }
        }

        echo json_encode(['code'=>1,'msg'=>'SUCCESS','data'=>$data]);
    }

    /**
     * 获取贡献页面数据
     * User:ZhengYaFeng
     * param Request $request
     *
     * @return mixed|string|void
     */
    public function getUserContribution(Request $request)
    {
        $page = $request->input('page');
        if(empty($page)) $page = 1;
        $start = ($page - 1) * 10;
        $plan_rate = DB::table('admini_systeminfo')
            ->select('anchor_proportions','plan_proportions')
            ->first();
        $data['contribution_total'] = intval(\Helpers::getUserRechargeContribution($this->loginUserInfo->id)*$plan_rate->plan_proportions/100);
        $data['contribution_left'] = intval(\Helpers::getUserContribution($this->loginUserInfo->id)*$plan_rate->plan_proportions/100);
        //获取单天最高
        $getDayTop = DB::select("
                select FROM_UNIXTIME(create_time,'%Y-%m-%d') as `ctime`,
                sum(`money`) as `topmoney` 
                from wj_member_contribution 
                where operate_status = 1 and 
                member_id='{$this->loginUserInfo->id}' 
                group by ctime 
                order by `topmoney` desc
            ");
        $data['getDayTop'] = !empty($getDayTop[0]->topmoney) ? $getDayTop[0]->topmoney : 0;
        $list = DB::table('member_contribution')
                            ->leftJoin('member','member.id','=','member_contribution.member_id')
                            ->select('member.avatar','member.username','member_contribution.money','member_contribution.create_time')
                            ->where('member_contribution.operate_status',1)
                            ->skip($start)
                            ->take(10)
                            ->get();
        $list = !empty($list) ? \Helpers::object_to_array($list) : [];
        $data['list'] = $list;
        echo json_encode(['code'=>1,'msg'=>'SUCCESS','data'=>$data]);
    }

    /**
     * 我的收藏-关注的主播
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function userLikeAnchors(Request $request)
    {
        $page = $request->input('page');
        if(empty($page)) $page = 1;
        $start = ($page - 1) * 10;

        $data = DB::table('member_fans')
            ->select('avatar as user_avatar','username','member.id as anchor_id','sign')
            ->leftJoin('member','member.id','=','member_fans.member_id_b')
            ->where('member_id_z',$this->loginUserInfo->id)
            ->where('type',1)->skip($start)->take(10)->get();

        if(!empty($data)){
            foreach ($data as $k => $v){
                $data[$k]->like_num = DB::table('member_fans')->where('member_id_b',$v->anchor_id)->where('type',1)->count();
                $data[$k]->level = $this->getUserLevel($v->anchor_id);
            }
        }
        echo json_encode(['code'=>1,'msg'=>'SUCCESS','data'=>$data]);
    }

    /**
     * 我的预约
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function getAnchorAppointment(Request $request)
    {
        //粉丝
        if($this->loginUserInfo->user_role == 3){
            $data['list'] =  DB::table('member_appointment')
                ->select('member_appointment.id as appoint_id','member_appointment.member_id','member.mobile','member.price','member.user_role','member.avatar','member.username','member_appointment.create_time as appointment_time','appointment.theme','appointment.duration')
                ->leftJoin('member','member.id','=','member_appointment.member_id')
                ->leftJoin('appointment','appointment.id','=','member_appointment.appointment_id')
                ->where('member_appointment.anchor_id',$this->loginUserInfo->id)
                ->where('member_appointment.status',1)
                ->orderBy('member_appointment.create_time','desc')
                ->get();
        }else{
            $data['list'] =  DB::table('member_appointment')
                ->select('member_appointment.id as appoint_id','member_appointment.member_id','member.mobile','member.price','member.user_role','member.avatar','member.username','member_appointment.create_time as appointment_time','appointment.theme','appointment.duration')
                ->leftJoin('member','member.id','=','member_appointment.anchor_id')
                ->leftJoin('appointment','appointment.id','=','member_appointment.appointment_id')
                ->where('member_appointment.member_id',$this->loginUserInfo->id)
                ->where('member_appointment.status',1)
                ->orderBy('member_appointment.create_time','desc')
                ->get();
        }
        if(!empty($data['list'])){
            foreach ($data['list'] as $k => $v){
                $data['list'][$k]->level = $this->getUserLevel($v->member_id);
            }
        }
        $data['num'] = count($data['list']);
        $data['price'] = $this->loginUserInfo->price;
        echo json_encode(['code'=>1,'msg'=>'SUCCESS','data'=>$data]);
    }


    /**
     * 预约主题列表
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function appointmentList(Request $request)
    {
        $anchor_id = $request->input('anchor_id');
        if(empty($anchor_id)) return json_encode(['code'=>-1002,'msg'=>'参数不合法']);

        $anchor_info = DB::table('member')->select("avatar",'username','price')->where('id',$anchor_id)->first();
        if(empty($anchor_info)) return json_encode(['code'=>-1009,'msg'=>'数据不存在']);
        $anchor_info->level = $this->getUserLevel($anchor_id);

        $data['anchor_info'] = \Helpers::object_to_array($anchor_info);

        $list = DB::table('member_consume')
            ->select(DB::raw('SUM(e_money) as close_num'))
            ->leftJoin('member','member.id','=','member_consume.member_id_b')
            ->where('member_consume.member_id_b',$anchor_id)
            ->where('member_consume.member_id',$this->loginUserInfo->id)
            ->first();

        if(!empty($list->close_num)){
            $data['close_num'] = $list->close_num;
        }else{
            $data['close_num'] = 0;
        }
        $data['list'] =  DB::table('appointment')->select('id as theme_id','theme','duration')->orderBy('id','desc')->get();
        echo json_encode(['code'=>1,'msg'=>'SUCCESS','data'=>$data]);
    }


    /**
     * 预约行为
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function doAppointment(Request $request)
    {
        $anchor_id = $request->input('anchor_id');
        $theme_id = $request->input('theme_id');
        if(empty($anchor_id) || empty($theme_id)) return json_encode(['code'=>-1002,'msg'=>'参数不合法']);

        //验证sign合法性
        $isValidSign = $this->checkSign($theme_id);
        if(empty($isValidSign)) exit(json_encode(['code'=>-9005,'msg'=>'sign无效']));
        //验证sign合法性

        $anchor_info = DB::table('member')->select("avatar",'username','price')->where('id',$anchor_id)->first();
        if(empty($anchor_info)) return json_encode(['code'=>-1009,'msg'=>'数据不存在']);

        $theme_info = DB::table('appointment')->where('id',$theme_id)->first();
        if(empty($theme_info)) return json_encode(['code'=>-1009,'msg'=>'数据不存在']);
        //预约价格
        $yyPrice = $anchor_info->price * $theme_info->duration;
        //当前用户预约
        $NowMoney = \Helpers::getUserLeftMoney($this->loginUserInfo->id);
        if($NowMoney < $yyPrice)  return json_encode(['code'=>-1009,'msg'=>'余额不足']);
        $time = time();
        //先在recharge表中记录一笔成功的记录，cousume表中做记录,member_appointment中做记录； 主播接通后，更新member_appointment的status值； 如果超过24h主播未接通，在recharge表、cousume中删除记录，更新member_appointment的status值
        //消费记录
        $insertC['theme_id'] = $theme_info->id;
        $insertC['member_id'] = $this->loginUserInfo->id;
        $insertC['create_time'] = $time;
        $insertC['type'] = 1;
        $insertC['e_money'] = $anchor_info->price * $theme_info->duration; //价格为: 主播单价*时长
        $insertC['chat_time'] = $theme_info->duration;
        $insertC['member_id_b'] = $anchor_id;
        $consume_id = DB::table('member_consume')->insertGetId($insertC);

        //recharge记录
        $insertR['member_id'] = $this->loginUserInfo->id;
        $insertR['e_money'] = '-'.$anchor_info->price * $theme_info->duration; //价格为: 主播单价*时长
        $insertR['operate_status'] = 1;
        $insertR['create_time'] = $time;
        $insertR['paid_at'] = $time;
        $insertR['type'] = 3;
        $insertR['chat_time'] = $theme_info->duration;
        $insertR['consume_id'] = $consume_id;
        DB::table('member_recharge')->insertGetId($insertR);

        //member_appointment表中记录
        $insertA['appointment_id'] = $theme_info->id;
        $insertA['member_id'] = $this->loginUserInfo->id;
        $insertA['anchor_id'] = $anchor_id;
        $insertA['create_time'] = $time;
        $insertA['status'] = 1;
        $insertA['consume_id'] = $consume_id;
        DB::table('member_appointment')->insertGetId($insertA);

        echo json_encode(['code'=>1,'msg'=>'SUCCESS']);
    }


    /**
     * 主播接通预约后，调用此接口
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function anchorAnswer(Request $request)
    {
        $appoint_id = $request->input('appoint_id');
        if(empty($appoint_id)) return json_encode(['code'=>-1002,'msg'=>'参数不合法']);

        $appoint_info = DB::table('member_appointment')->where('id',$appoint_id)->first();
        if(empty($appoint_info)) return json_encode(['code'=>-1009,'msg'=>'数据不存在']);

        $upArr = array('status'=>2);
        DB::table('member_appointment')->where('id',$appoint_id)->update($upArr);
        $getAppInfo = DB::table('member_appointment')->where('id',$appoint_id)->select('anchor_id','consume_id','appointment_id')->first();
        $findUser = DB::table('member')->where('id',$getAppInfo->anchor_id)->where('status',1)->select('price')->first();
        $getDuration = DB::table('appointment')->where('id',$getAppInfo->appointment_id)->select('duration')->first();
        $insertR['member_id'] = $getAppInfo->anchor_id;
        $insertR['create_time'] = time();
        $insertR['e_money'] = $findUser->price*$getDuration->duration;
        $insertR['operate_status'] = 1;
        $insertR['type'] = 3;
        $insertR['consume_id'] = $getAppInfo->consume_id;
        DB::table('member_recharge')->insertGetId($insertR);
        echo json_encode(['code'=>1,'msg'=>'SUCCESS']);
    }

    /**
     * 主播删除预约 - 在recharge表、cousume中删除记录，更新member_appointment的status值
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function anchorDelAppoint(Request $request)
    {
        $appoint_id = $request->input('appoint_id');
        if(empty($appoint_id)) return json_encode(['code'=>-1002,'msg'=>'参数不合法']);

        $appoint_info = DB::table('member_appointment')->where('id',$appoint_id)->first();
        if(empty($appoint_info)) return json_encode(['code'=>-1009,'msg'=>'数据不存在']);

        $upArr = array('status'=>3);
        DB::table('member_appointment')->where('id',$appoint_id)->update($upArr);

        DB::table('member_consume')->where('id',$appoint_info->consume_id)->delete();
        DB::table('member_recharge')->where('consume_id',$appoint_info->consume_id)->delete();

        echo json_encode(['code'=>1,'msg'=>'SUCCESS']);
    }

    /**
     * 观看付费视频
     * User: Xiahuiqin
     *
     * @param Request $request
     *
     * @return mixed|string|void
     */
    public function payRechargeVideo(Request $request)
    {
        $video_id = $request->input('video_id');
        $anchor_id = $request->input('anchor_id');
        if(empty($video_id) || empty($anchor_id)) return json_encode(['code'=>-1002,'msg'=>'参数不合法']);

        $findConsume =  DB::table('member_consume')->where('video_id',$video_id)->where('type',3)->where('member_id',$this->loginUserInfo->id)->first();

        if(!empty($findConsume)) return json_encode(['code'=>1,'msg'=>'SUCCESS']);

        //不能给自己打赏
        if($anchor_id == $this->loginUserInfo->id) return json_encode(['code'=>-1002,'msg'=>'参数不合法']);

        $userLeftMoney = \Helpers::getUserLeftMoney($this->loginUserInfo->id);
        if($GLOBALS['systemInfo']->video_price > $userLeftMoney)  return json_encode(['code'=>-1012,'msg'=>'E币不足']);

        $insertArr['member_id'] = $this->loginUserInfo->id;
        $insertArr['member_id_b'] = $anchor_id;
        $insertArr['video_id'] = $video_id;
        $insertArr['type'] = 3;
        $insertArr['e_money'] = $GLOBALS['systemInfo']->video_price;
        $insertArr['create_time'] = time();

        $insertDb = DB::table('member_consume')->insertGetId($insertArr);
        if(!empty($insertDb)){
            //往e币表加数据
            $insertR['member_id'] = $this->loginUserInfo->id;
            $insertR['create_time'] = time();
            $insertR['e_money'] = '-'.$GLOBALS['systemInfo']->video_price;
            $insertR['operate_status'] = 1;
            $insertR['type'] = 3;
            $insertR['consume_id'] = $insertDb;

            $insertReDb = DB::table('member_recharge')->insertGetId($insertR);
            //主播增加E币
            $insertRA['member_id'] = $anchor_id;
            $insertRA['create_time'] = time();
            $insertRA['e_money'] = $GLOBALS['systemInfo']->video_price;
            $insertRA['operate_status'] = 1;
            $insertRA['type'] = 3;
            $insertRA['consume_id'] = $insertDb;
            DB::table('member_recharge')->insertGetId($insertRA);

            echo json_encode(['code'=>1,'msg'=>'SUCCESS']);
        }else{
            echo json_encode(['code'=>-1001,'msg'=>'服务器异常']);
        }
    }

}